/**
 * 
 */
package com.shine.cotrun.exp;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

/**
 * 导出EXCEL
 * @author zsy
 *
 */
public class ExportToText<D> extends Export<D> {
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	private BufferedWriter fw;
	private String encoding;
	
	public ExportToText(ExportConf conf) {
		super(conf);
		this.extName = ".txt";
		this.encoding = "utf-8";
	}
	
	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	@Override
	public void init() {
		super.init();
		try {
			fw = new BufferedWriter(new OutputStreamWriter(this.outputStream, encoding));
			
			StringBuffer row = new StringBuffer();
			//写入头部信息
			for (int i = 0 ; i < conf.getColumnSize(); i++) {
				row.append(conf.getField(i).getExpColumnName());
				if (i + 1 < conf.getColumnSize()) {
					row.append('|');
				}
			}
			row.append("\r\n");
			fw.write(row.toString());
			fw.flush();
		} catch(Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void export(Collection<D> data) throws Exception {
		if (data == null || data.size() == 0) {
			return;
		}
		StringBuffer row = new StringBuffer();
		for (Object o : data) {
			Class<?> c = o.getClass();
			row = new StringBuffer();
			for (int i = 0 ; i < conf.getColumnSize(); i++) {
				Method m = c.getMethod(conf.toMethod(conf.getField(i).getExpPropertie()));
				Object val = m.invoke(o);
				if (val != null) {
					if (val instanceof Date) {
						row.append(sdf.format(val));
					} else {
						row.append(val);
					}
				}
				if (i + 1 < conf.getColumnSize()) {
					row.append('|');
				}
			}
			row.append("\r\n");
			fw.write(row.toString());
		}
		fw.flush();
	}
	
	@Override
	public String end() {
		try {
			fw.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return super.end();
		
	}
}
